package com.java.sample.mac;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class MacAddressUtil {

    public static List<InetAddressInfo> getValidInetAddress(){
        List<InetAddressInfo> inetAddressInfos = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                // 跳过回环接口和虚拟接口
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                // 获取MAC地址
                byte[] mac = networkInterface.getHardwareAddress();
                if (mac != null && mac.length > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                    String macAddress = sb.toString();

                    InetAddressInfo inetAddressInfo = new InetAddressInfo();
                    inetAddressInfo.setMac(macAddress);
                    inetAddressInfo.setName(networkInterface.getName());
                    inetAddressInfo.setDisplayName(networkInterface.getName());

                    List<String> ipv4s = new ArrayList<>();
                    List<String> ipv6s = new ArrayList<>();

                    // 获取IP地址
                    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress inetAddress = inetAddresses.nextElement();
                        // 排除回环地址
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            ipv4s.add(inetAddress.getHostAddress());
                        } else if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
                            ipv6s.add(inetAddress.getHostAddress());
                        }
                    }

                    inetAddressInfo.setIpv4s(ipv4s);
                    inetAddressInfo.setIpv6s(ipv6s);
                    inetAddressInfos.add(inetAddressInfo);
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return inetAddressInfos;
    }


}
